package org.xiaoxiao.servlet;

import org.xiaoxiao.dao.BookVoteDao;
import org.xiaoxiao.pojo.Book;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin")
public class AdminServlet extends HttpServlet {
    private final BookVoteDao dao = new BookVoteDao();

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 检查登录状态
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("admin") == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        // 传递书籍列表
        List<Book> books = dao.getAllBooks();
        request.setAttribute("books", books);
        request.getRequestDispatcher("/admin.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置请求体的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");

        // 检查登录状态
        HttpSession session = request.getSession();
        if (session.getAttribute("admin") == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        String action = request.getParameter("action");
        String bookId = request.getParameter("bookId");

        if ("delete".equals(action) && bookId != null) {
            dao.deleteBook(bookId);
            session.setAttribute("message", "书籍已删除");
        }
        else if ("add".equals(action)) {
            Book newBook = new Book();
            newBook.setId(request.getParameter("id"));
            newBook.setTitle(request.getParameter("title"));
            newBook.setAuthor(request.getParameter("author"));
            newBook.setVotes(0);

            if (dao.addBook(newBook)) {
                session.setAttribute("message", "书籍添加成功");
            } else {
                session.setAttribute("error", "添加失败: ID可能已存在");
            }
        } else if ("update".equals(action)) {
            String id = request.getParameter("id");
            String title = request.getParameter("title");
            String author = request.getParameter("author");
            if (dao.updateBook(id, title, author)) {
                session.setAttribute("message", "书籍信息更新成功");
            } else {
                session.setAttribute("error", "更新失败: ID不存在");
            }
        }

        response.sendRedirect("admin");
    }
}
